package zkdemo;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

public class CuratorApiDemo {
	
	CuratorFramework client;
	
	@Before
	public void init() {
		client = CuratorFrameworkFactory.builder()
				.connectString("192.168.10.188:2181")
				.sessionTimeoutMs(5000)
				.connectionTimeoutMs(3000)
				.retryPolicy(new ExponentialBackoffRetry(1000, 3))
				.namespace("zk-book")
				.build();
		client.start();
	}
	
	@Test
	public void testClient() {
		/**
		 * public static CuratorFramework newClient(String connectString, int sessionTimeoutMs, int connectionTimeoutMs, RetryPolicy retryPolicy)
		 * 
		 * connectString:指定服务器列表
		 * sessionTimeoutMs:会话超时时间 默认60000ms
		 * connectionTimeoutMs:链接创建超时时间 默认15000ms
		 * retryPolicy:重试策略
		 * public ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries)
		 * baseSleepTimeMs:初始sleep时间
		 * maxRetries:最大重试次数
		 */
		CuratorFramework client = CuratorFrameworkFactory
				.newClient("192.168.10.188:2181", 5000, 3000, 
						new ExponentialBackoffRetry(1000, 3));
		
		client.start();
	}
	
	@Test
	public void testFluentClient() {
		CuratorFramework client = CuratorFrameworkFactory.builder()
			.connectString("192.168.10.188:2181")
			.sessionTimeoutMs(5000)
			.connectionTimeoutMs(3000)
			.retryPolicy(new ExponentialBackoffRetry(1000, 3))
			.namespace("zk-book")
			.build();
		
		client.start();
	}
	
	//创建节点
	@Test
	public void testCreate() throws Exception {
		String path = client.create()
			.creatingParentContainersIfNeeded()
			.withMode(CreateMode.EPHEMERAL)
			.forPath("/c1/c1-1");
		
		System.out.println("path="+path);
		Thread.sleep(10000);
	}
	
	//读出数据
	@Test
	public void testGetData() throws Exception {
		Stat stat = new Stat();
		System.out.println(
				new String(client.getData().storingStatIn(stat).forPath("/c1"))
		);
		System.out.println("stat="+stat);
	}
}
